# coding=utf-8
from datetime import datetime

from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.modules.debt_repay import Debtor_repay
from comment.modules import db
from comment.modules.user import User
from comment.ultils.decorators import Login_required
from financial.resorces.transaction.serializer import RepayPlanSerializer


class RepayPlan(Resource):
    '''还款的资源类'''

    # 拦截器他会在LoginOut的所有的视图函数都会在执行视图函数之前，做一下装饰器的拦截
    method_decorators = [Login_required]  # 使用了登录拦截的装饰器

    def get(self):
        '''查询某一个（匹配成功）的借款，债权所对应的还款计划'''
        rp = RequestParser()

        rp.add_argument('debt_id') #债权的ID

        args = rp.parse_args()

        debt_id = int(args.get('debt_id'))

        repay_list = Debtor_repay.query.filter(Debtor_repay.claimsId == debt_id).all()

        data = RepayPlanSerializer(repay_list).to_dict()
        return {
            'msg': 'sucess',
            'data': data
        }

    def post(self):
        '''还款到指定的某个还款某一期'''
        rp = RequestParser()

        rp.add_argument('repay_id') #还款计划ID
        rp.add_argument('repayAmount') #当期还款的金额

        args = rp.parse_args()

        repay_id = int(args.get('repay_id'))
        repay_money = float(args.get('repayAmount'))

        user_id  = g.user_id
        user = User.query.filter(User.id == user_id).first()

        #判断用户余额是否足够还款
        if user.accountInfo.balance < repay_money:
            return {
                'message':'可用余额不足',
                'code':215
                }
        else:
            #扣除余额
            user.accountInfo.balance = float(user.accountInfo.balance) - repay_money
            repay = Debtor_repay.query.filter(Debtor_repay.id == repay_id).first()
            #更改还款状态
            repay.isReturned = 1
            #记录还款的日期
            repay.recordDate = datetime.now()

            db.session.commit()
            return {'msg':'success'}
















